#include "fdb_port.h"
#include "fmc.h"

#define Flash_ReadWord(address)     (*((volatile uint32_t*)(address)))
#define Flash_ReadHalfWord(address) (*((volatile uint16_t*)(address)))
#define Flash_ReadByte(address)     (*((volatile uint8_t*)(address)))

void FDB_Read_Flash(uint32_t address, void * p_data, uint32_t size)
{
	uint32_t i = 0;

	for(i = 0; i < size; i++)
	{
		((uint8_t *)p_data)[i] = Flash_ReadByte(address + i);
	}
}

void FDB_Erase_Flash(uint32_t address)
{
	fmc_erase_sector_by_address(address);
}

void FDB_Write_Flash(uint32_t address, void * p_data, uint32_t size)
{
	uint32_t i = 0;
	
	fmc_unlock();
	fmc_flag_clear(FMC_FLAG_END | FMC_FLAG_OPERR | FMC_FLAG_WPERR | FMC_FLAG_PGMERR | FMC_FLAG_PGSERR);
	for(i = 0; i < size; i++)
	{
		fmc_byte_program(address + i, ((uint8_t *)p_data)[i]);
	}
	fmc_lock();
}

void FDB_Copy_Flash(uint32_t new_address, uint32_t raw_address, uint32_t size)
{
	uint32_t i = 0;
	
	fmc_unlock();
	fmc_flag_clear(FMC_FLAG_END | FMC_FLAG_OPERR | FMC_FLAG_WPERR | FMC_FLAG_PGMERR | FMC_FLAG_PGSERR);
	for(i = 0; i < size; i++)
	{
		fmc_byte_program(new_address + i, Flash_ReadByte(raw_address + i));
	}
	fmc_lock();
}
